const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  port: 3306
};

// 创建连接池 - 不指定数据库
let pool = mysql.createPool(dbConfig);

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error);
    return false;
  }
}

// 初始化数据库和表
async function initializeDatabase() {
  try {
    console.log('开始初始化数据库...');
    
    // 创建数据库
    await pool.query('CREATE DATABASE IF NOT EXISTS chat_app');
    console.log('数据库chat_app创建成功');
    
    // 关闭旧的连接池
    await pool.end();
    console.log('旧连接池已关闭');
    
    // 创建新的连接池，这次包含数据库名
    const newDbConfig = { ...dbConfig, database: 'chat_app' };
    pool = mysql.createPool(newDbConfig);
    console.log('新连接池已创建，连接到chat_app数据库');
    
    // 检查数据库中是否已有数据
    const [existingApiKeys] = await pool.query(`
      SELECT COUNT(*) as count FROM information_schema.tables 
      WHERE table_schema = 'chat_app' AND table_name = 'api_keys'
    `);
    
    const apiKeysTableExists = existingApiKeys[0].count > 0;
    if (apiKeysTableExists) {
      const [keyCount] = await pool.query("SELECT COUNT(*) as count FROM api_keys");
      if (keyCount[0].count > 0) {
        console.log(`API密钥表已存在，包含 ${keyCount[0].count} 条记录`);
      }
    }
    
    // 创建用户表
    await pool.query(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        email VARCHAR(100) UNIQUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);
    console.log('用户表创建成功');
    
    // 创建API密钥表
    await pool.query(`
      CREATE TABLE IF NOT EXISTS api_keys (
        id INT AUTO_INCREMENT PRIMARY KEY,
        \`key\` TEXT NOT NULL, 
        provider VARCHAR(50) NOT NULL,
        endpoint VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);
    console.log('API密钥表创建成功');
    
    // 只有在表为空时才进行测试
    if (!apiKeysTableExists) {
      console.log('执行API密钥表测试...');
      // 测试API密钥表
      await pool.query('INSERT INTO api_keys (`key`, provider, endpoint) VALUES (?, ?, ?)', 
        ['test_key', 'test_provider', 'http://test.com']
      );
      const [testRows] = await pool.query('SELECT * FROM api_keys WHERE `key` = ?', ['test_key']);
      if (testRows.length > 0) {
        console.log('API密钥表测试成功');
        await pool.query('DELETE FROM api_keys WHERE `key` = ?', ['test_key']);
      } else {
        throw new Error('API密钥表测试失败');
      }
    }
    
    console.log('数据库和表初始化成功');
  } catch (error) {
    console.error('数据库初始化失败:', error);
    throw error;
  }
}

// 返回当前连接池
function getPool() {
  return pool;
}

// 初始化数据库
initializeDatabase().catch(error => {
  console.error('初始化失败，程序将退出:', error);
  process.exit(1);
});

module.exports = {
  getPool,
  initializeDatabase,
  testConnection
}; 